<?php

namespace App\Http\Controllers\Admin\Category;

use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use App\Model\Category;
use App\Http\Requests\Categorys\Categorys;

class CategoryController extends Controller
{
    /**
     * 分类页的显示
     * @author chenxinbin@xinbin882@gmail.com
     * @return 返回Categorys的数据给到视图
     */
    public function index()
    {
        $categorys = Category::select(['id', 'sname', 'pid', 'path', 'descr', 'state'])->orderBy(DB::raw('concat(path, id)'))->paginate(10);
        foreach ($categorys as $key => $value) {
            $value['nbsp'] = str_repeat("&nbsp;",substr_count($value['path'],",")*16); 
        }
        return view ('Admin/Categorys/product-category', ['categorys' => $categorys]);
    }

     /**
     * 加载添加根的页面
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('Admin/Categorys/product-category-add');
    }

    /**
     * 分类的数据的添加
     * @author chenxinbin@xinbin882@gmail.com
     * @param  $request是添加的数据
     * @return 返回添加成功/添加失败
     */
    public function store(Categorys $request)
    {
        $sname = $request->input('sname');
        $info = Category::select('sname', 'id')->where('sname', $sname)->first();
        if($info){
            return back()->with('errorTip', '添加失败,类名已存在');
        }
        $re = Category::insert([
                'sname' => $request->input('sname'),
                'pid'   => $request->input('pid'),
                'descr'  =>  $request->input('descr'),
                'state'   => $request ->input('state'),
                'path'    => $request->input('path'),
                'created_at' => date('Y-m-d', time()),
                'updated_at' => date('Y-m-d', time()),
                ]);

        if($re){

            Redis::del('indexSort');//删除前台页面的分类
            return redirect('Admin/product-category')->with('msg', '添加成功');

        }else{

            return back()->with('errorTip', '添加失败');

        }
       
    }

   
    /**
     * 加载添加子分类的视图
     * @author chenxinbin@xinbin882@gmail.com
     * @return 添加子分类的视图
     */
    public function childAdd($id)
    {

         $data = Category::select(['id', 'path', 'sname', 'pid'])->where('id', $id)->first();
        //获取路径中的,个数，并判断是否个数是否大于等于3则不能添加。
        $n = substr_count($data->path,',');
        if($n >= 3){
            return redirect('/Admin/product-category')->with('errorTip', '子类不能超过3个，添加失败');
         } else {
        return view ("Admin/Categorys/product-category-childAdd", ['data' => $data]);
        }
    }

    /**
     * 添加子分类
     * @author chenxinbin@xinbin882@gmail.com
     * @param  int  $id
     * @return 返回自定义信息
     */
    public function childInsert(Request $request)
    {
        $this->validate($request, [
            'sname' => 'required',
            'path' => 'required',
            'descr' => 'required',
        ],
        [
            'sname.required' => '类别名必填',
            'path.required' => '路径必填',
            'descr.required' => '描述必填',
        ]);
        // $sname = $request->input('sname');
        // $info = Category::select('sname', 'id')->where('sname', $sname)->first();
        // if($info){
        //     return back()->with('errorTip', '添加失败,类名已存在');
        // }
        $id = $request->input('id');
        // 根据id去查上级的关键字
        $key = Category::select('id', 'path')->where('id', $id)->first();
        $path = "{$key->path}{$id},";
        $bool = Category::insert([
            'sname'=> $request->input('sname'),
            'pid' => $request->input('id'),
            'path' => $path,
            'descr' =>$request->input('descr'),
            'state' =>$request->input('state'),
            'created_at' => date('Y-m-d', time()),
            'updated_at' => date('Y-m-d', time()),
          ]);

          if ($bool) {
            Redis::del('detailSort');
            Redis::del('indexSort');//删除前台页面的分类
            return redirect('/Admin/product-category')->with('msg', '增加成功');
          }
          return back()->with('errorTip', '增加失败');
    }
  

    /**
     *  
     * @author chenxinbin@xinbin882@gmail.com
     * @param  int  $id
     * @return   
     */
    public function show(request $request )
    {
        $name = $request->input('sname');
        $name = "%".$name."%";
       //根据$id查询对应商品数据，并且放到页面
        $categorys = Category::select(['id', 'sname', 'pid', 'path', 'descr', 'state'])->orderBy(DB::raw('concat(path, id)'))->where('sname', 'like', $name)->get();

        foreach ($categorys as $key => $value) {
            // dd($value->sname);
            $value['nbsp'] = str_repeat("&nbsp;",substr_count($value['path'],",")*16); 
        }
 
        return view ('Admin/Categorys/product-findcategory', ['categorys' => $categorys]);
    }

    /**
     * 分类的编辑的视图
     * @author chenxinbin@xinbin882@gmail.com
     * @param  int  $id
     * @return 查询到修改的数据
     */
    public function edit($id)
    {
        $oneCategory = Category::select(['id', 'sname', 'pid', 'path', 'descr', 'state'])->where('id', $id)->first();
        $categorysAll = Category::select('id', 'sname', 'pid', 'path')->orderBy(DB::raw('concat(path, id)'))->get();
        foreach ($categorysAll as $key => $value) {

            $value['nbsp'] = str_repeat("&nbsp;",substr_count($value['path'],",")*6); 
        }
        // dd($oneCategory);
        return view('Admin/Categorys/product-category-edit', ['oneCategory' => $oneCategory, 'categorysAll' => $categorysAll]);
    }

    /**
     * 更新某一个分类
     * @author chenxinbin@xinbin882@gmail.com
     * @param  $request 添加的数据
     * @param  int  $id
     * @return 返回修改成功/修改失败
     */
    public function update(Categorys $request, $id)
    {
        $this->validate($request, [
            'sname' => 'required',
            'descr' => 'required',
        ],
        [
            'sname.required' => '类别名必填',
            'descr.required' => '描述必填',
        ]);
        // $pid = $request->input('pid');
        // $data = Category::select(['id', 'path', 'sname', 'pid'])->where('id', $pid)->first();
        // //获取路径中的,个数，并判断是否个数是否大于等于3则不能添加。
        // // dd($data);
        // $n = substr_count($data->path,',');
        // // dd($n);
        // if($n >= 3){

        //     return back()->with('errorTip', '子类不能超过3个，添加失败');

        //  } else {

            $pid = $request->input('pid');

            $id  = $request->input('id');
            
            $data = Category::select(['pid', 'path','id'])->where('id', $pid)->first();
            $sondata = Category::select(['pid', 'path','id'])->where('id', $id)->first();
            // dd($data['path'],$data['pid'],$data['id']);
            // dd($sondata['path']);
            // if($sondata['path'] == '0,')
            // {
            // 	 return back()->with('errorTip', '不能修改根分类');

            // } else {

            	// $path = $data['path'].$pid.',';

            // }
           
            // dd($path,$pid);
            $bool =Category::where('id', $id)
                     ->update([
                          // 'path' => $path,
                          'sname' => $request->input('sname'),
                          'pid' =>  $pid,
                          'descr' => $request->input('descr'),
                          'state' => $request->input('state'),
                         ]);
     
            if ($bool) {
              Redis::del('detailSort');
              Redis::del('indexSort');//删除前台页面的分类
              return redirect('/Admin/product-category')->with('msg', '修改成功');
            }

            return back()->with('errorTip', '修改失败');


        // }
 
        
    }

    /**
     * 删除某一个分类
     * @author chenxinbin@xinbin882@gmail.com
     * @param  int  $id
     * @return  $data = ['  'status' => 0, 'msg'    =>'分类删除成功',] 或者$data = ['  'status' => 1, 'msg'    =>'分类删除失败,请稍后再试！',] 
     */
    public function destroy($id)
    {
        
        //删除分类
        $res=Category::select(['pid', 'id'])->where('id', $id)->delete();

        //删除父类，会将子类的pid改为顶级分类
        Category::where('pid',$id)->update(['pid' => 0, 'path' => "0,"]);
         if ($res) {
             Redis::del('detailSort');
             Redis::del('indexSort');//删除前台页面的分类
                   $data = [
                           'status' => 0,
                           'msg'    =>'分类删除成功',
                           ];
             } else {
                 $data = [
                           'status' => 1,
                           'msg'    =>'分类删除失败,请稍后再试！',
                           ];
            }
        return $data;
    }
}